//
//  VVEmoticonKeyBoard.swift
//  Weibo
//
//  Created by 王惠平 on 2017/4/7.
//  Copyright © 2017年 Will Wang. All rights reserved.
//

import UIKit

class VVEmoticonKeyBoard: UIView {
    
    //懒加载 toolBar
    fileprivate lazy var toolBar:VVEmoticonToolBar = VVEmoticonToolBar()

    //表情视图
    fileprivate lazy var emoticonCollectionView: UICollectionView = {
       
        let flowLayout = UICollectionViewFlowLayout()
        
        //设置水平滚动
        flowLayout.scrollDirection = .horizontal
        
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: flowLayout)
        
        //设置背景颜色
        collectionView.backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)

        //分页效果
        collectionView.isPagingEnabled = true
        
        //隐藏滚动指示器
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.showsVerticalScrollIndicator = false
        
        //去掉弹簧效果
        collectionView.bounces = false
        
        //注册cell 
        collectionView.register(VVEmoticonViewCell.self, forCellWithReuseIdentifier: EmoticonViewCellIdentifier)
        
        //设置数据代理
        collectionView.dataSource = self
        
        //设置代理
        collectionView.delegate = self
        
        return collectionView
        
    }()
    
    //页数指示器
    fileprivate lazy var pageControl: UIPageControl = {
        
        let pageCtr = UIPageControl()
        
        //使用kvc给私有成员变量赋值
        pageCtr.setValue(UIImage(named:"compose_keyboard_dot_normal"), forKey: "_pageImage")
        pageCtr.setValue(UIImage(named:"compose_keyboard_dot_selected"), forKey: "_currentPageImage")
    
        //隐藏单页
        pageCtr.hidesForSinglePage = true
        
        return pageCtr
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    fileprivate func setupUI() {
                
        //pageControlVarName()
        
        //默认滚动默认表情这组数据
        let normalIndexPath = IndexPath(item: 0, section: 1)
        
        //滚动到指定indexPath, 因为表情视图数据还没有加载完成,滚动不了, 需要等到数据加载完成,需要主线程异步
        //等到加载完成数据后表情视图有数据了才能滚动
        DispatchQueue.main.async {
            
            self.emoticonCollectionView.scrollToItem(at: normalIndexPath, at: [], animated: false)
            
            self.setPageControlData(indexPath: normalIndexPath)
        }
        
        //添加视图
        addSubview(toolBar)
        addSubview(emoticonCollectionView)
        addSubview(pageControl)
        
        //设置约束
        toolBar.snp.makeConstraints { (make) in
            
            make.leading.trailing.bottom.equalTo(self)
            make.height.equalTo(35)
        }
        
        emoticonCollectionView.snp.makeConstraints { (make) in
            
            make.leading.trailing.top.equalTo(self)
            
            make.bottom.equalTo(toolBar.snp.top)
        }
        
        pageControl.snp.makeConstraints { (make) in
            
            make.bottom.equalTo(emoticonCollectionView)
            
            make.centerX.equalTo(emoticonCollectionView)
            
            make.height.equalTo(10)
        }
        
        //设置点击表情按钮的闭包
        toolBar.didSelectedEmoticonClosure = {[weak self] (type: VVEmoticonType)->() in

            let indexPath: IndexPath
            
            switch type {
                
            case .recent:
                
                //print("最近")
                indexPath = IndexPath(item: 0, section: 0)
                
            case .normal:
                
                //print("默认")
                indexPath = IndexPath(item: 0, section: 1)
                
            case .emoji:
                
                //print("emoji")
                indexPath = IndexPath(item: 0, section: 2)
                
            case .lxh:
                
                //print("浪小花")
                indexPath = IndexPath(item: 0, section: 3)
    
            }
        
            //滚动到指定indexPath
            self?.emoticonCollectionView.scrollToItem(at: indexPath, at: [], animated: false)
        
        }
    }
    
    //根据indexPath绑定数据
    fileprivate func setPageControlData(indexPath: IndexPath) {
        
        //获取某种表情的页数
        self.pageControl.numberOfPages = VVEmoticonTools.sharedTools.allEmoticonArray[indexPath.section].count
        
        //当前选中的页数索引
        self.pageControl.currentPage = indexPath.item
    }
    
    //扩展
    //使用runtime获取UIPageControl的成员变量
    func pageControlVarName() {
        
        //类型里面成员变量的个数
        var outCount: UInt32 = 0
        
        //获取类型里面的成员变量
        if let ivarList = class_copyIvarList(UIPageControl.self, &outCount) {
            
           //遍历成员变量的个数获取成员变量名称
            for i in 0..<outCount {
                
              //根据下标获取对应的成员变量参数
                let ivar = ivarList[Int(i)]
                
                //获取变量的名字
                let cName = ivar_getName(ivar)!
                
                //c语言字符串转string类型
                let name = String(cString: cName)
                
                print(name)
                
                let cType = ivar_getTypeEncoding(ivar)!
                
                //获取变量对应的类型
                let type = String(cString: cType)
                
                print(type)
                
                
            }
            
        }
        
    }
    
    //获取表情视图的大小
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        //获取布局对象
        let flowLayout = emoticonCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
        
        //设置每项的大小等于视图的大小
        flowLayout.itemSize = emoticonCollectionView.size
        
        //设置每一项的间距
        flowLayout.minimumLineSpacing = 0
        flowLayout.minimumInteritemSpacing = 0
        
    }
}

//代理实现
extension VVEmoticonKeyBoard: UICollectionViewDataSource, UICollectionViewDelegate {
    
    //返回多少组
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        
        return VVEmoticonTools.sharedTools.allEmoticonArray.count
    }
    
    //每组显示多少个cell
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return VVEmoticonTools.sharedTools.allEmoticonArray[section].count
    }
    
    //获取cell
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: EmoticonViewCellIdentifier, for: indexPath) as! VVEmoticonViewCell
        
        cell.indexPath = indexPath
        
        //获取这一页显示表情数组数据
        let emoticonArray = VVEmoticonTools.sharedTools.allEmoticonArray[indexPath.section][indexPath.item]
        
        cell.emoticonArray = emoticonArray
        
        return cell
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        //水平方向的内容的中心点
        let contentCenterX = scrollView.contentOffset.x + scrollView.width * 0.5

        if let indexPath = emoticonCollectionView.indexPathForItem(at: CGPoint(x: contentCenterX, y: scrollView.height * 0.5)) {
            
            //获取对应组的索引
            let section = indexPath.section
            
            //根据索引选中对应的按钮
            toolBar.selectButton(section: section)
            
            self.setPageControlData(indexPath: indexPath)
        }
        
    }
}
